//
//  SHLogin.m
//  youjian03
//
//  Created by 常琼 on 14/10/9.
//  Copyright (c) 2014年 com.shouhuobao. All rights reserved.
//

#import "SHLogin.h"
#import "MBProgressHUD+MJ.h"
#import "FMDB.h"
#import "SHTheSoftTableViewController.h"
#import <AVFoundation/AVFoundation.h>

@interface SHLogin ()<UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet UITextField *phoneno;
@property (weak, nonatomic) IBOutlet UITextField *code;
@property (weak, nonatomic) IBOutlet UIButton *loginbtn;//登录按钮

@property (weak, nonatomic) IBOutlet UIButton *btn_msd;
@property (weak, nonatomic)  UIButton *button;//获取验证码
@property(strong,nonatomic) NSTimer *timeer;

@property(nonatomic,copy) NSString *token;//服务器返回一个token
@property(nonatomic,copy) NSString *inputphone;//输入的手机号
@property(nonatomic,copy) NSString *inputcode;//输入的code

@property (weak, nonatomic) IBOutlet UIButton *isgree;

- (IBAction)click_gree:(UIButton *)sender;

@property(nonatomic,weak) UIButton *isagree;//同意协议

@property(nonatomic,copy) NSString *returncode;
- (IBAction)getCode:(UIButton *)sender;

- (IBAction)getnot:(UIButton *)sender;//没收到?

- (IBAction)clickxieyi:(UIButton *)sender;


- (IBAction)NewLogin:(UIButton *)sender;




@end

@implementation SHLogin
    static int no = 30;//倒计时秒数

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        

    }
    return self;
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [NSThread sleepForTimeInterval:.1];
    [self.phoneno becomeFirstResponder];
    
    
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    //"登录"标题
    UIButton *youjian =  [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 69, 17)];
    [youjian setTitle:@"快速登录" forState:UIControlStateNormal];
    [youjian setTitleColor:[UIColor redColor] forState: UIControlStateNormal];
    
    [youjian setFont:[UIFont fontWithName:@"Helvetica-Bold" size:20]];
    
    youjian.userInteractionEnabled = NO;

    self.navigationItem.titleView = youjian;

    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithImageName:@"btn_qx" highImageName:@"btn_qx" target:self action:@selector(close)];
    
    self.phoneno.keyboardType =UIKeyboardTypePhonePad;

    self.btn_msd .hidden = YES;

    

    
    self.loginbtn.enabled = NO;
    self.code.delegate = self;
    
    self.code.text = @"";
    
    

}



 /**
 *  点击关闭按钮
 */
-(void)close
{
    [self dismissViewControllerAnimated:NO completion:nil];
    
}

-(void)dealloc
{
    [self.view endEditing:YES];
}

/**
 *  获取验证码
 */
- (IBAction)getCode:(UIButton *)sender {
    //发送网络请求
    
    self.button = sender;
    [self.code becomeFirstResponder];
    
    self.timeer =   [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerFireMethod) userInfo:nil repeats:YES];
    sender.userInteractionEnabled = NO;
    
    
    NSDictionary *msg = @{@"phone":self.phoneno.text};
    [SHHTTPTOOL PostWithDic:msg andAction:@"userCode" success:^(id responseObj) {

        NSDictionary *msg =  responseObj[@"msg"];
        
        HMLog(@"验证码是:%@",msg[@"code"]);
        self.returncode = msg[@"code"];
        
        
    } failure:^(NSError *error) {
        
    }];
}

-(void)timerFireMethod
{
    if (no != 0)
    {
  
        [self.button setBackgroundImage:[UIImage imageNamed:@"getcodeing"] forState:UIControlStateNormal];
        [self.button setTitle:[NSString stringWithFormat:@"发送中..%d",no] forState:UIControlStateNormal];
        
        [self.button setImage:nil forState:UIControlStateNormal];
        
        no--;
    }
    else
    {
        self.btn_msd .hidden = NO;
        self.button.userInteractionEnabled = YES;
        no = 30;
        [self.button setTitle:nil forState:UIControlStateNormal];
        self.button .selected = YES;
        
        [self.timeer invalidate];
        [self.button setImage:[UIImage imageNamed:@"getagain__normal"] forState:UIControlStateNormal];
        [self.button setImage:[UIImage imageNamed:@"getagain__press"] forState:UIControlStateHighlighted];
        
    }
    

}
/**
 *  点击忘记了按钮
 */
- (IBAction)getnot:(UIButton *)sender {
    NSDictionary *dic = @{@"phone":self.phoneno.text};
    [SHHTTPTOOL PostWithDic:dic andAction:@"userCallCode" success:^(id responseObj) {
        
        HMLog(@"resp:%@",responseObj);
        NSDictionary *result  = responseObj[@"msg"];
        
        HMLog(@"语音验证码:%@",result[@"code"]);
        NSString *code = result[@"code"];
        self.returncode = code;
        
    } failure:^(NSError *error) {
        
        
    }];
    
    
}
- (IBAction)clickxieyi:(UIButton *)sender {

    SHTheSoftTableViewController *vc = [[SHTheSoftTableViewController alloc] init];
    [self.navigationController pushViewController:vc animated:NO];
    
    
}
/**
 *  点击登录
 */
- (IBAction)NewLogin:(UIButton *)sender {
    
    if(self.isagree .selected ==NO)//同意协议
    {
        
    if ([self.code.text isEqualToString:self.returncode])//登录成功1(验证码输入正确)
    {
        
        
        //先保存一下电话号码
        self.inputphone = self.phoneno.text;
        
        
        
        //发送httppost 获得 token***************************************************************************
        NSDictionary *dic = @{@"phone":self.phoneno.text,@"code":self.code.text};

        
        [SHHTTPTOOL PostWithDic:dic andAction:@"userLogin" success:^(id responseObj) {
            NSLog(@"userlogin is %@",responseObj);
            NSDictionary *result = responseObj[@"msg"];
            
            HMLog(@"返回的token是%@",result[@"token"]);
            
            
            
            self.token  = result[@"token"];
//            if( self.token == nil)
//            {
//                self.token = @"TOKENISNULL";
//            }
            
            //登录成功之后将手机号码存入数据库证明该手机号是有效的
            NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
            NSString *filename = [doc stringByAppendingPathComponent:@"youjian.sqlite"];
            FMDatabase *db = [FMDatabase databaseWithPath:filename];
            [db open];
            NSString *sql= [NSString stringWithFormat:@"insert into userinfo (phone,token) values('%@','%@')",self.phoneno.text,self.token];
            
            
            BOOL ok =  [db executeUpdate:sql];

            if (ok)
            {
                HMLog(@"插入ok");
            }
            else
            {
                HMLog(@"插入失败");
            }
           
            /********************************--sqlEnd--***********************************************/
            
            
            //发送通知给menu 顺便传过去一些信息
            NSString *finaltoken =  [self.token copy];
            //TODO: 登录崩溃
            NSDictionary *dic = @{@"key":self.inputphone,@"key2":finaltoken};
            [[NSNotificationCenter defaultCenter] postNotificationName:@"LOGINED" object:nil userInfo:dic];
            
            
            
            //play music
            NSURL *url =  [[NSBundle mainBundle] URLForResource:@"ding.wav" withExtension:nil];
            
            SystemSoundID soundId = 0;
            AudioServicesCreateSystemSoundID((__bridge CFURLRef)(url), &soundId);
            
            //-play music
            
            AudioServicesPlayAlertSound(soundId);
            
            AudioServicesDisposeSystemSoundID(soundId);

            
            [self dismissViewControllerAnimated:NO completion:nil];
            
        } failure:^(NSError *error) {
            
            
        }];
        
    }
    else//登录失败
        
    {
        //弹出提示框
        self.code.text = @"";
        self.loginbtn.enabled = NO;
        //清空文本框
        [MBProgressHUD showError:@"登录失败"];
        
    }
    }
    else//不同意协议
    {
        MBProgressHUD  *HUD = [[MBProgressHUD alloc] initWithView:self.view];
        [self.view addSubview:HUD];
        HUD.labelFont = [UIFont systemFontOfSize:14];
        HUD.labelText =@"请阅读并同意《软件许可及服务协议》";
        
        HUD.mode = MBProgressHUDModeText;
        
        [HUD showAnimated:YES whileExecutingBlock:^{
            sleep(2.5);
        } completionBlock:^{
            [HUD removeFromSuperview];
        }];

    }
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    

    
    NSUInteger oldLength = [textField.text length];
    NSUInteger replacementLength = [string length];
    NSUInteger rangeLength = range.length;
    
    NSUInteger newLength = oldLength - rangeLength + replacementLength;
    if (newLength==4)
    {
    self.loginbtn .enabled = YES;
    }
    else
    {
        self.loginbtn .enabled = NO;
    }
    
    
    return YES;
}
/**
 *  点击阅读并同意
 */
- (IBAction)click_gree:(UIButton *)sender {
    
    sender.selected = !sender.selected;
    self.isagree = sender;
    
    
    
    
}
@end
